package com.huima.blog.service.impl;

import com.huima.blog.model.vo.file.UploadFileRspVO;
import com.huima.blog.service.AdminFileService;
import com.huima.blog.common.Response;
import com.huima.blog.common.enums.ResponseCodeEnum;
import com.huima.blog.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.UUID;

/**
 * @description: TODO
 **/
@Service
@Slf4j
public class AdminFileServiceImpl implements AdminFileService {

    @Value("${file.baseUrl}")
    private String baseUrl;

    @Override
    public Response uploadFile(MultipartFile file) {
        String rootPath = getProjectRootDirectory();
        File rootDir = new File(rootPath + "/src/main/resources/img");
        if(!rootDir.exists()){
            rootDir.mkdirs();
        }
        String path = rootDir.getPath();
        int idx = file.getOriginalFilename().lastIndexOf(".");
        String suffix = file.getOriginalFilename().substring(idx);
        String fileName = UUID.randomUUID() + suffix;
        String fullPath = path + "/" + fileName;
        try {
            file.transferTo(new File(fullPath));
            return Response.success(UploadFileRspVO.builder().url(baseUrl + fileName).build());
        }catch (IOException e){
            log.error("==> 上传文件异常: ", e);
            throw new BizException(ResponseCodeEnum.UPLOAD_FILE_ERROR);
        }
    }

    private static String getProjectRootDirectory() {
        // 获取当前类的ClassLoader
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        if (loader != null) {
            try {
                // 获取当前类的URL地址
                URL url = loader.getResource("");

                if (url != null && "file".equalsIgnoreCase(url.getProtocol())) {
                    // 将URL转换成File对象
                    File file = new File(url.toURI());

                    // 返回上两级目录 (当前目录为classes,上一级为target,再上一级为项目路径)
                    return file.getParentFile().getParentFile().getAbsolutePath();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return "";
    }
}
